package com.ltu.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.core.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Objects;
import com.ltu.biz.OrderServiceBiz;
import com.ltu.config.wx.payment.config.WxPayProperties;
import com.ltu.domain.mp_entity.PayCallBackEntity;
import com.ltu.domain.mp_entity.PayRecord;
import com.ltu.domain.mp_entity.customize.CompanyEntity;
import com.ltu.mapper.PayRecordMapper;
import com.ltu.model.request.base.BaseFilterPageReq;
import com.ltu.model.request.base.BaseIdReq;
import com.ltu.model.response.base.CodeDataResp;
import com.ltu.payment.config.WxAppPayConfig;
import com.ltu.payment.util.RsaUtil;
import com.ltu.payment.util.XmlUtils;
import com.ltu.service.PayCallBackService;
import com.ltu.service.PayRecordService;
import com.ltu.service.customize.CompanyService;
import com.ltu.service.impl.BaseServiceImpl;
import com.ltu.util.ext.wx.wxCore.WeChatUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;


/**
 * <p>
 * 支付记录 前端控制器
 * </p>
 *
 * @author 若尘
 * @since 2022-02-21
 */
@Slf4j
@RestController
@RequestMapping("/payRecord")
@Api(tags= "支付记录")
@RequiredArgsConstructor(onConstructor = @__(@Autowired)) 
public class PayRecordController extends BaseServiceImpl<PayRecordMapper, PayRecord>{
	private final  PayCallBackService payCallBackService;
	private final  PayRecordService payRecordService;
	private final  OrderServiceBiz orderServiceBiz;
	private final  CompanyService companyService;
	private final  CompanyEntity  wxMaMiniAppCfg;
	@Value("${wx.pay.mchKey}")
	private String serviceMchKey;
	   
    @ApiOperation(value="获取分页列表")
    @RequestMapping(value="/getMePage", method= RequestMethod.POST)
    public CodeDataResp<Page<PayRecord>> getMePage(@RequestBody  BaseFilterPageReq<PayRecord> req ) {
    	return super.getMePage(req);
    }
    
    @ApiOperation(value="获取列表")
    @RequestMapping(value="/getList", method= RequestMethod.POST)
    public CodeDataResp<List<PayRecord>> getList(@RequestBody  BaseFilterPageReq<PayRecord> req ) {
        return super.getMeList(req);
    }

    @ApiOperation(value="新增/保存")
    @RequestMapping(value="/edit", method= RequestMethod.POST)
    public CodeDataResp edit(@RequestBody PayRecord req) {
        return super.edit(req);
    }
    @ApiOperation(value="批量修改数据")
    @RequestMapping(value="/edits", method= RequestMethod.POST)
    public CodeDataResp edits(@RequestBody List<PayRecord> reqs) {
    	super.saveOrUpdateBatch(reqs);
    	return   CodeDataResp.valueOfSuccessEmptyData();
    }
    
 	@ApiOperation(value="获取详情")
    @RequestMapping(value="/getDetail", method= RequestMethod.GET)
    public CodeDataResp getDetail(@RequestBody BaseIdReq baseIdReq) {
        return super.getDetail(baseIdReq);
    }

    @ApiOperation(value="删除")
    @RequestMapping(value="/remove", method= RequestMethod.GET)
    public CodeDataResp remove(@RequestBody BaseIdReq baseIdReq) {
        return super.remove(baseIdReq);
    }
    
     @ApiOperation(value="删除s")
    @RequestMapping(value="/removes", method= RequestMethod.POST)
    public CodeDataResp removes(@RequestBody List<Integer> ids) {
    		super.removeByIds(ids);
        return CodeDataResp.valueOfSuccessEmptyData();
    }

 	/**
 	 * @date 2019年10月18日
 	 * @author 若尘
 	 * @Description 微信官方支付结果通知地址
 	 * 模拟微信，body参数如下：
 	 * 	<xml><appid><![CDATA[wxb13efd9ccba504e6]]></appid>
 	 * <bank_type><![CDATA[OTHERS]]></bank_type>
 	 * <cash_fee><![CDATA[1]]></cash_fee>
 	 * <fee_type><![CDATA[CNY]]></fee_type>
 	 * <is_subscribe><![CDATA[N]]></is_subscribe>
 	 * <mch_id><![CDATA[1642662433]]></mch_id>
 	 * <nonce_str><![CDATA[1683528766616]]>
 	 * </nonce_str><openid><![CDATA[o1IDp4kq_EeiQq5goAczNQgoTgtE]]></openid>
 	 * <out_trade_no><![CDATA[D20230508145246597000003029852]]></out_trade_no>
 	 * <result_code><![CDATA[SUCCESS]]></result_code>
 	 * <return_code><![CDATA[SUCCESS]]></return_code>
 	 * <sign><![CDATA[021F407A041F515E576EB25919B04183]]></sign>
 	 * <time_end><![CDATA[20230508145308]]></time_end>
 	 * <total_fee>1</total_fee>
 	 * <trade_type><![CDATA[JSAPI]]></trade_type>
 	 * <transaction_id><![CDATA[4200001867202305081800133759]]></transaction_id></xml>
 	 * 
 	 */
 	@ApiOperation(value = "微信官方支付结果通知地址")
 	@RequestMapping(value = "/wxNotify", method = { RequestMethod.POST,RequestMethod.GET })
 	public void wxNotify( HttpServletRequest request, HttpServletResponse response) throws Exception {
 		StringBuilder sb = new StringBuilder();
 		BufferedReader in = request.getReader();// 获取正文内容
 		String line;
 		while ((line = in.readLine()) != null) {
 			sb.append(line);
 		}
 		String xml = sb.toString();
 		log.info("================收到微信回调，回调信息：\n {}",xml);
 		Map<String, String> result = XmlUtils.toMap(xml.getBytes(), "utf-8");
 		// 签名验证
 		String verifySign = result.get("sign");
 		result.remove("sign");
 	
// 		boolean verifyFlag = WeChatUtils.verifySign2(result, wxMaMiniAppCfg.getMchKeyApi2(), verifySign);// 商户模式
 		boolean verifyFlag = WeChatUtils.verifySign2(result,serviceMchKey , verifySign);// 服务商模式
 		if (verifyFlag == false) {
 			log.error("50000", "签名验证失败");
 			// 先响应微信收到通知
 			WeChatUtils.responsePayMessage(response, "签名失败");
 			return;
 		}

 		boolean excludeRepeatFlag = WeChatUtils.wxPayMsgExcludeRepeat(result.get("out_trade_no"),
 				result.get("transaction_id"), result.get("time_end"));// 消息排重
 		if (excludeRepeatFlag) {
 			log.error("50000", "微信支付回调消息重复");
 			// 先响应微信收到通知
 			WeChatUtils.responsePayMessage(response, "消息重复");
 			return;
 		}

 		// 先响应微信收到通知
 		WeChatUtils.responsePayMessage(response, "OK");
 		// 执行回调业务
 		QueryWrapper<PayRecord> wrapper=new QueryWrapper<PayRecord>();
 		wrapper.lambda().eq(PayRecord :: getOrderNo, result.get("out_trade_no")).last("limit 1");
 		PayRecord payRecord = payRecordService.getOne(wrapper);// 获取订单
 		
 		if(Objects.equal(payRecord.getIsHandle(), (byte)1))
 			return;
 		payCallBackService.createWXCallBack(result, payRecord);
 		orderServiceBiz.payRecordCallBack(payRecord);

 	}
 	
    
   



}

